package cc.rengu.redp.bizimpl.utils;

import org.apache.commons.io.FileUtils;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
/*import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;*/

public class ExcelDownload {

	public static void getExcel(HttpServletRequest request, HttpServletResponse response, String fileName) throws IOException {
		/*
		// 下载Excel
		String path = request.getSession().getServletContext().getRealPath("upload") + File.separator + fileName;
		File file = new File(path);  
        HttpHeaders headers = new HttpHeaders(); 
        String name = new String(fileName.getBytes("UTF-8"), "iso-8859-1");//为了解决中文名称乱码问题 
        headers.setContentDispositionFormData("attachment", name);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);		// HttpStatus.CREATED 不支持ie
        */
		
		// 下载Excel
		String path = request.getSession().getServletContext().getRealPath("upload") + File.separator + fileName;
		File file = new File(path);
		if (! file.exists()) {
			return;
		}
        OutputStream out = null;
        try {
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            String header = request.getHeader("User-Agent");
            if(header.toLowerCase().contains("firefox")){
				BASE64Encoder base64Encoder = new BASE64Encoder();
				response.setHeader("Content-Disposition", "attachment; filename==?UTF-8?B?"+(new String(base64Encoder.encode(fileName.getBytes("UTF-8"))))+"?=" );
			}else {
				response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
			}
            out = response.getOutputStream();
            out.write(FileUtils.readFileToByteArray(file));
            out.flush();
        } catch (IOException e) {

        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {

                }
            }
            // 此处仅提供模板文件的下载，所以不应该删除模板文件，注释掉
            /*
            File f = new File(path);
    		// 如果文件存在，删除
            if (f.exists()) { 
    			f.delete();
    		}
    		*/
        }
	}
	
	public static String downimg(HttpServletRequest request, HttpServletResponse response, String path) throws IOException {
		/*
		//下载Excel
		String path = request.getSession().getServletContext().getRealPath("upload") + File.separator + fileName;
		File file = new File(path);  
        HttpHeaders headers = new HttpHeaders(); 
        String name = new String(fileName.getBytes("UTF-8"), "iso-8859-1");//为了解决中文名称乱码问题 
        headers.setContentDispositionFormData("attachment", name);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);		//HttpStatus.CREATED 不支持ie
        */
		
		// 下载Excel
		response.setContentType("text/html;charset=utf-8");
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {

		}
		String fileName = path.substring(path.lastIndexOf("\\")+1);
		// path=path.replace(fileName, "");
		java.io.BufferedInputStream bis = null;
		java.io.BufferedOutputStream bos = null;
	
		// String ctxPath =path.replace(fileName, "");
		// String downLoadPath = ctxPath + fileName;
//		System.out.println(path);

		try {
			long fileLength = new File(path).length();
			response.setContentType("application/x-msdownload;");
			response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
			response.setHeader("Content-Length", String.valueOf(fileLength));
			bis = new BufferedInputStream(new FileInputStream(path));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {

		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {

				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {

				}
			}
		}
		return null;
	}

}
